<?php 

/**
 * Thing 控制器
 * @author keluo <pycorvn@yeah.net>
 * @since 2012-12-3 11:06:04
 *
 */
class ThingController extends SCController {
	
	public function __construct() {
		parent::__construct();
	}
	
	public function index($thing_id) {
		$tencent = new Tencent();
		$tencent->pushActivity($thing_id);
	}
	
	/**
	 * 单个thing展示页
	 */
	public function view($thing_id) {
		$thing_id = intval($thing_id);
		($thing = $this->model->from('sc_thing')->where('thing_id = '.$thing_id)->findOne()) || $this->redirect->to();
		$user_info = SCScabish::model('user')->getBasicInfo($thing->user_id);
				
		if($thing->type == 'photo') {
			$photos = $this->model->reset()->from('sc_photo')->where('thing_id = '.$thing->thing_id)->order('photo_id DESC')->find();
			foreach($photos as $k=>$photo) {
				$photos[$k]->thumbs = unserialize($photo->thumbs);
			}
			$thing->photos = $photos;
		} elseif($thing->type == 'video') {
			$thing->video = $this->model->reset()->from('sc_video')->where('thing_id = '.$thing->thing_id)->findOne();
		} elseif($thing->type == 'music') {
			$thing->music = $this->model->reset()->from('sc_music')->where('thing_id = '.$thing->thing_id)->findOne();
		}
		
		SCPaging::setRecordPerPage(10);
		$comments = $this->model->reset()->selectPage('
			c.*, u.nickname, u.avatar, r.nickname AS reply_name 
			FROM sc_comment AS c LEFT JOIN sc_user AS u ON c.user_id = u.user_id 
			LEFT JOIN sc_user AS r ON c.reply_id = r.user_id 
			WHERE c.thing_id = '.$thing_id.' ORDER BY c.post_date DESC');
		
		require $this->view->load();
	}
	
	/**
	 * 接收用户发送的thing
	 */
	public function send() {
		($user_id = SCScabish::model('user')->checkLogin()) || $this->ajaxFail('user_not_login');
		switch(SCRequest::post('type')) {
			case 'text':
				$thing_id = $this->saveText($user_id);
			break;
			case 'photo':
				$thing_id = $this->savePhoto($user_id);
			break;
			case 'music':
				$thing_id = $this->saveMusic($user_id);
			break;
			case 'video':
				$thing_id = $this->saveVideo($user_id);
			break;
		}
		$tencent = new Tencent();
		$tencent->pushActivity($thing_id); // 推送动态到QQ空间
		
		$this->ajaxSuccess();
	}
	
	/**
	 * 保存纯文字的thing
	 */
	protected function saveText($user_id) {
		$thing_id = $this->model->from('sc_thing')->insert(array(
			'user_id' => $user_id,
			'type' => 'text',
			'text' => SCRequest::post('text'),
			'post_date' => date('Y-m-d H:i:s')
		));
		return $thing_id;
	}
	
	/**
	 * 保存带图片的thing
	 */
	protected function savePhoto($user_id) {
		$thing_id = $this->model->from('sc_thing')->insert(array(
			'user_id' => $user_id,
			'type' => 'photo',
			'text' => SCRequest::post('text'),
			'post_date' => date('Y-m-d H:i:s')
		));
		$image_tmpnames = SCRequest::post('image_tmpname');
		$image_extensions = SCRequest::post('image_extension');
		$target_dir = SCConfig::get('UPLOAD_PATH').'/'.date('Ym');
		file_exists($target_dir) || @mkdir($target_dir, 777, true);
		file_exists($target_dir.'/80') || @mkdir($target_dir.'/80', 777, true);
		file_exists($target_dir.'/200') || @mkdir($target_dir.'/200', 777, true);
		file_exists($target_dir.'/400') || @mkdir($target_dir.'/400', 777, true);
		$data = array();
		foreach($image_tmpnames as $key=>$tmpname) {
			$extension = $image_extensions[$key];
			$image_tmp_path = SCConfig::get('UPLOAD_PATH').'/tmp/'.$tmpname;
			
			list($left, $right) = explode(' ', microtime());
			$file_name = $right.(str_pad($left*100000000, 8, STR_PAD_LEFT)).'.'.$extension;
			
			$thumb_80 = Thumbnail::generate($image_tmp_path, $target_dir.'/80/'.$file_name, 80, 80);
			$thumb_200 = Thumbnail::generate($image_tmp_path, $target_dir.'/200/'.$file_name, 200, 200);
			$thumb_400 = Thumbnail::generate($image_tmp_path, $target_dir.'/400/'.$file_name, 400, 400);
			$thumbs = array(
				80 => array('path' => date('Ym').'/80/'.$file_name, 'width' => $thumb_80['width'], 'height' => $thumb_80['height']),
				200 => array('path' => date('Ym').'/200/'.$file_name, 'width' => $thumb_200['width'], 'height' => $thumb_200['height']),
				400 => array('path' => date('Ym').'/400/'.$file_name, 'width' => $thumb_400['width'], 'height' => $thumb_400['height'])
			);
			
			list($width, $height) = getimagesize($image_tmp_path);
			rename($image_tmp_path, $target_dir.'/'.$file_name);
			array_push($data, array(
				'thing_id' => $thing_id,
				'user_id' => 1,
				'is_link' => 0,
				'path' => date('Ym').'/'.$file_name,
				'width' => $width,
				'height' => $height,
				'thumbs' => serialize($thumbs)
			));
		}
		$this->model->reset()->from('sc_photo')->insert($data);
		return $thing_id;
	}
	
	/**
	 * 保存带音乐链接的thing
	 */
	protected function saveMusic($user_id) {
		$thing_id = $this->model->from('sc_thing')->insert(array(
			'user_id' => $user_id,
			'type' => 'music',
			'text' => SCRequest::post('text'),
			'post_date' => date('Y-m-d H:i:s')
		));
	
		$image_tmp_path = SCConfig::get('UPLOAD_PATH').'/tmp/'.SCRequest::post('image_tmp_name');
		$target_dir = SCConfig::get('UPLOAD_PATH').'/'.date('Ym');
		file_exists($target_dir) || @mkdir($target_dir, 777, true);
		list($left, $right) = explode(' ', microtime());
		$file_name = $right.(str_pad($left*100000000, 8, STR_PAD_LEFT)).'.'.SCRequest::post('image_extension');
	
		$thumb = Thumbnail::generate($image_tmp_path, $target_dir.'/'.$file_name, 200, 200);
		@unlink($image_tmp_path);
		
		$this->model->from('sc_music')->insert(array(
			'thing_id' => $thing_id,
			'user_id' => 1,
			'url' => SCRequest::post('url'),
			'width' => SCRequest::post('width'),
			'height' => SCRequest::post('height'),
			'preview_path' => date('Ym').'/'.$file_name,
			'preview_width' => $thumb['width'],
			'preview_height' => $thumb['height']
		));
		return $thing_id;
	}
	
	/**
	 * 保存带视频链接的thing
	 */
	protected function saveVideo($user_id) {
		$thing_id = $this->model->from('sc_thing')->insert(array(
			'user_id' => $user_id,
			'type' => 'video',
			'text' => SCRequest::post('text'),
			'post_date' => date('Y-m-d H:i:s')
		));
		
		$image_tmp_path = SCConfig::get('UPLOAD_PATH').'/tmp/'.SCRequest::post('image_tmp_name');
		$target_dir = SCConfig::get('UPLOAD_PATH').'/'.date('Ym');
		file_exists($target_dir) || @mkdir($target_dir, 777, true);
		list($left, $right) = explode(' ', microtime());
		$file_name = $right.(str_pad($left*100000000, 8, STR_PAD_LEFT)).'.'.SCRequest::post('image_extension');
		
		$thumb = Thumbnail::generate($image_tmp_path, $target_dir.'/'.$file_name, 200, 200);
		@unlink($image_tmp_path);
		
		$this->model->from('sc_video')->insert(array(
			'thing_id' => $thing_id,
			'user_id' => 1,
			'url' => SCRequest::post('url'),
			'width' => SCRequest::post('width'),
			'height' => SCRequest::post('height'),
			'preview_path' => date('Ym').'/'.$file_name,
			'preview_width' => $thumb['width'],
			'preview_height' => $thumb['height']
		));
		return $thing_id;
	}
	
	/**
	 * 获取更早之前发布的thing
	 * @param integer $divide 分界点thing_id
	 * @param boolean $later true则获取thing_id大于divide的thing，否则获取小于divide的thing
	 * @param integer $number 获取条数
	 * @param integer $host_user_id 用户ID，如果设置了该参数表示获取该用户的thing
	 */
	public function getThings($divide = 0, $later = true, $number = 20, $host_user_id = 0) {
		($user_id = SCScabish::model('user')->checkLogin()) || $this->ajaxFail('user_not_login');
		
		$where = 'user_id = '.($host_user_id ? $host_user_id : $user_id);
		$op = $later ? '>' : '<';
		$where .= intval($divide) ? ' AND thing_id '.$op.' '.intval($divide) : '';
		$things = $this->model->from('sc_thing')
			->where($where)
			->order('thing_id DESC')
			->limit(intval($number))
			->find();
		foreach($things as $key=>$thing) {
			if($thing->type == 'photo') {
				$photos = $this->model->reset()->from('sc_photo')->where('thing_id = '.$thing->thing_id)->order('photo_id DESC')->find();
				foreach($photos as $k=>$photo) {
					$photos[$k]->thumbs = unserialize($photo->thumbs);
				}
				$thing->photos = $photos;
				$things[$key] = $thing;
			} elseif($thing->type == 'video') {
				$thing->video = $this->model->reset()->from('sc_video')->where('thing_id = '.$thing->thing_id)->findOne();
			} elseif($thing->type == 'music') {
				$thing->music = $this->model->reset()->from('sc_music')->where('thing_id = '.$thing->thing_id)->findOne();
			}
			$thing->comment_num = $this->model->reset()->field('COUNT(*)')->from('sc_comment')->where('thing_id = '.$thing->thing_id)->findScalar();
		}
		$this->ajaxSuccess($things);
	}
	
	/**
	 * 删除指定的thing
	 * @param integer $thing_id
	 */
	public function delete($thing_id) {
		($user_id = SCScabish::model('user')->checkLogin()) || $this->ajaxFail('user_not_login');
		$model = $this->model->reset();
		$thing = $model->from('sc_thing')->where('thing_id = '.$thing_id.' AND user_id = '.$user_id)->findOne();
		$thing || $this->ajaxFail('user_cannot_access');
		
		switch($thing->type) {
			case 'photo' :
				SCScabish::model('photo')->dropPhotoByThingId($thing->thing_id);
			break;
			case 'video':
				SCScabish::model('video')->dropVideoByThingId($thing->thing_id);
			break;
			case 'music':
				SCScabish::model('music')->dropMusicByThingId($thing->thing_id);
			break;
		}
		$model->from('sc_thing')->where('thing_id = '.$thing_id)->delete();
		$model->reset()->from('sc_comment')->where('thing_id = '.$thing_id)->delete();
		
		$this->ajaxSuccess();
	}
}